package com.nineclock.security.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@Configuration
@EnableWebSecurity
//开启注解控制权限, prePostEnabled = true 允许使用@PreAuthorize (前置,(常用)), @PostAuthorize（后置）
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Bean
    public PasswordEncoder passwordEncoder(){
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder;
    }

//    // @Bean 把方法的返回值对象存储到 spring ioc容器中
//    @Override
//    @Bean
//    protected UserDetailsService userDetailsService() {
//
//
//        //在内存中构建用户
//        InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
//        //构建用户信息  {noop} 不加密
//        UserDetails userDetails1 = User.withUsername("itheima").password(passwordEncoder().encode("123456")).authorities("ROLE_ADMIN", "P1").build();
//
//        inMemoryUserDetailsManager.createUser(userDetails1);
//
//        UserDetails userDetails2 = User.withUsername("itcast").password(passwordEncoder().encode("123456")).authorities("ROLE_USER", "O1").build();
//
//        inMemoryUserDetailsManager.createUser(userDetails2);
//
//        return inMemoryUserDetailsManager;
//    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()   //表单登录   只要表单是 /login 就认为你在登录
            .and()
            .logout().and()  //退出功能  只要请求/logout就会清除session，跳转到登录页面
            .csrf().disable()  //关闭跨站请求伪造
            .authorizeRequests()  //认证请求配置
            .antMatchers("/register").permitAll()  // antMatchers 配置请求路径  permitAll  不登录也能访问(开放授权)
//            .antMatchers("/hello").hasRole("ADMIN")  //hasRole 必须拥有某角色才能访问  ,此方法 前缀必须是 ROLE_,且必须大写
//            .antMatchers("/say").hasAuthority("O1")  //hasAuthority 必须拥有某权限才能访问 , 此方法 没有要求，任意角色权限都可以写
            .anyRequest().authenticated(); //其他请求路径，只要认证了就可以访问
    }
}
